const express = require('express')
const router = express.Router()
const db = require('../config/db')
const ipToCity = require('../utils/ipToCity')

// 获取文章列表
router.get('/list', async (req, res) => {
  try {
    const { page = 1, pageSize = 10, category } = req.query
    const offset = (page - 1) * pageSize

    let query = `
      SELECT articles.*, users.nickname AS authorName, users.avatar_url AS authorAvatar
      FROM articles
      JOIN users ON articles.author_id = users.id
      WHERE articles.deleted_at IS NULL
    `
    let countQuery =
      'SELECT COUNT(*) as total FROM articles WHERE deleted_at IS NULL'
    const queryParams = []

    if (category) {
      query += ' AND articles.category = ?'
      countQuery += ' AND category = ?'
      queryParams.push(category)
    }

    query +=
      ' ORDER BY articles.is_top DESC, articles.created_at DESC LIMIT ? OFFSET ?'
    queryParams.push(parseInt(pageSize), offset)

    const [articles] = await db.query(query, queryParams)
    const [totalCount] = await db.query(countQuery, category ? [category] : [])
    const camelCaseArticles = articles.map((article) => ({
      id: article.id,
      title: article.title,
      content: article.content,
      category: article.category,
      tags: article.tags,
      authorId: article.author_id,
      authorName: article.authorName,
      authorAvatar: article.authorAvatar,
      publishIp: article.publish_ip,
      viewCount: article.view_count,
      likeCount: article.like_count,
      commentCount: article.comment_count,
      status: article.status,
      isTop: article.is_top,
      createdAt: article.created_at,
      updatedAt: article.updated_at,
      deletedAt: article.deleted_at,
      publishLocation: article.publish_location,
    }))
    res.json({
      data: {
        list: camelCaseArticles,
        total: totalCount[0].total,
        page: parseInt(page),
        pageSize: parseInt(pageSize),
      },
      message: '获取成功',
      code: 200,
    })
  } catch (error) {
    res.status(500).json({ data: null, message: error.message, code: 500 })
  }
})

// 获取文章详情
router.get('/detail/:id', async (req, res) => {
  try {
    const { id } = req.params

    const query = `
      SELECT articles.*, users.nickname AS authorName, users.avatar_url AS authorAvatar
      FROM articles
      JOIN users ON articles.author_id = users.id
      WHERE articles.id = ? AND articles.deleted_at IS NULL
    `
    const [articles] = await db.query(query, [id])

    if (articles.length === 0) {
      return res.status(404).json({
        data: null,
        message: '文章不存在',
        code: 404,
      })
    }

    const article = articles[0]
    const articleDetail = {
      id: article.id,
      title: article.title,
      content: article.content,
      category: article.category,
      tags: article.tags,
      authorId: article.author_id,
      authorName: article.authorName,
      authorAvatar: article.authorAvatar,
      publishIp: article.publish_ip,
      viewCount: article.view_count,
      likeCount: article.like_count,
      commentCount: article.comment_count,
      status: article.status,
      isTop: article.is_top,
      createdAt: article.created_at,
      updatedAt: article.updated_at,
      deletedAt: article.deleted_at,
      publishLocation: article.publish_location,
    }

    res.json({
      data: articleDetail,
      message: '获取成功',
      code: 200,
    })
  } catch (error) {
    res.status(500).json({ data: null, message: error.message, code: 500 })
  }
})

// 发布文章
router.post('/publish', async (req, res) => {
  try {
    const {
      title,
      content,
      category,
      tags,
      authorId,
      authorName,
      authorAvatar,
    } = req.body

    if (!title || !content || !category || !authorId || !authorName) {
      return res.status(400).json({
        data: null,
        message: '缺少必要参数',
        code: 400,
      })
    }

    // 获取客户端IP地址
    const ip =
      req.headers['x-forwarded-for']?.split(',')[0] ||
      req.connection.remoteAddress ||
      req.socket.remoteAddress ||
      req.ip ||
      '0.0.0.0'

    // 将IP转换为城市名称
    const publishLocation = await ipToCity(ip)
    console.log('publishLocation', publishLocation)

    const [result] = await db.query(
      'INSERT INTO articles (title, content, category, tags, author_id, author_name, author_avatar, publish_ip, publish_location) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
      [
        title,
        content,
        category,
        JSON.stringify(tags || []),
        authorId,
        authorName,
        authorAvatar,
        ip,
        publishLocation,
      ]
    )

    res.status(201).json({
      data: { id: result.insertId },
      message: '发布成功',
      code: 200,
    })
  } catch (error) {
    res.status(500).json({ data: null, message: error.message, code: 500 })
  }
})

// 删除文章（软删除）
router.post('/delete', async (req, res) => {
  try {
    const { id, author_id } = req.body

    if (!id || !author_id) {
      return res.status(400).json({
        data: null,
        message: '缺少必要参数',
        code: 400,
      })
    }

    // 检查文章是否存在且属于该作者
    const [articles] = await db.query(
      'SELECT id FROM articles WHERE id = ? AND author_id = ? AND deleted_at IS NULL',
      [id, author_id]
    )

    if (articles.length === 0) {
      return res.status(404).json({
        data: null,
        message: '文章不存在或无权限删除',
        code: 404,
      })
    }

    // 软删除文章
    await db.query(
      'UPDATE articles SET deleted_at = CURRENT_TIMESTAMP WHERE id = ?',
      [id]
    )

    res.json({
      data: null,
      message: '删除成功',
      code: 200,
    })
  } catch (error) {
    res.status(500).json({ data: null, message: error.message, code: 500 })
  }
})

module.exports = router
